/*
 * @Author: wuhao930406 1148547900@qq.com
 * @Date: 2023-05-26 11:32:31
 * @LastEditors: wuhao930406 1148547900@qq.com
 * @LastEditTime: 2023-10-07 13:30:07
 * @FilePath: /utools_web/src/components/Floder/index.jsx
 * @Description:
 *
 * Copyright (c) 2023 by ${git_name_email}, All Rights Reserved.
 */
import IconFont from '@/components/IconFont';
import { doFetch } from '@/utils/doFetch';
import { Input, message } from 'antd';
import { useLayoutEffect, useState } from 'react';

function Addfolder({ projectId, directoryId, refresh }) {
  return (
    <div className="center" style={{ gap: 6 }}>
      <Input
        allowClear
        placeholder="文件夹名称"
        style={{ width: 188 }}
        defaultValue={'新建文件夹'}
        autoFocus
        onPressEnter={async (e) => {
          e.stopPropagation();
          let res = await doFetch({
            url: '/directory',
            params: {
              name: e.target.value,
              projectId,
              parentId: directoryId,
            },
          });
          if (res?.code === 0) {
            refresh();
          }
        }}
      />
    </div>
  );
}

function Rename({ curitem, refresh }) {
  const [val, setval] = useState();
  const [addon, setaddon] = useState(null);

  useLayoutEffect(() => {
    if (curitem?.name.indexOf('.') === -1 || ['folder'].includes(curitem?.type)) {
      setval(curitem?.name);
    } else {
      const filearr = curitem?.name?.split('.');
      const filename = filearr?.filter((it, i) => i !== filearr?.length - 1).join('.');
      const addon = filearr?.filter((it, i) => i === filearr?.length - 1).join('.');
      setval(filename);
      setaddon(addon);
    }
  }, [curitem?.name]);

  return (
    <div className="center" style={{ gap: 6 }}>
      <Input
        placeholder="编辑名称"
        prefix={<IconFont type="icon-rename" />}
        style={{ width: 188 }}
        value={val}
        onChange={(e) => {
          setval(e.target.value);
        }}
        onPressEnter={async (e) => {
          e.stopPropagation();
          if (!e.target.value) {
            message.error('文件名为空');
            return;
          }
          const path = curitem?.type === 'folder' ? '/directory/' : '/directory/file/';
          const newname = addon ? val + `.${addon}` : val;
          let res = await doFetch({
            url: path + curitem?.id,
            params: { name: newname },
            method: 'PUT',
          });
          if (res?.code === 0) {
            refresh();
          }
        }}
      />
    </div>
  );
}

export default {
  Addfolder,
  Rename,
};
